package com.tckj.boot.modules.domain.obj.category.application;

import com.alibaba.fastjson.JSON;
import com.tckj.boot.common.utils.BeanUtils;
import com.tckj.boot.modules.domain.obj.category.application.dto.CategoryDto;
import com.tckj.boot.modules.domain.obj.category.model.Category;
import com.tckj.boot.modules.domain.obj.category.model.CategoryRespository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName CategoryService
 * @Description
 * @Author icodebug
 * @Date 19-7-12 上午11:33
 */
@Service
public class CategoryService {

    @Autowired
    private CategoryRespository respository;

    public List<CategoryDto> getAllTreeData(){
        List<Category> categoryList = respository.findByParentIsNull(Sort.by(Sort.Direction.ASC, "sort"));
        return getTreeData(categoryList);
    }

    private List<CategoryDto> getTreeData(List<Category> categories){
        List<CategoryDto> categoryDtos = new ArrayList<>();
        categories.stream().forEach(category -> {
            CategoryDto categoryDto = BeanUtils.map(category,CategoryDto.class);
            categoryDto.setId(category.getId());
            if (category.getChild()){
                categoryDto.setChildren(getTreeData(respository.findByParent(category,Sort.by(Sort.Direction.ASC, "sort"))));
            }
            categoryDtos.add(categoryDto);
        });
        System.out.println(JSON.toJSONString(categoryDtos));
        return categoryDtos;
    }

}
